package com.lagou.binding;

import com.lagou.pojo.Configuration;
import com.lagou.sqlsession.SqlSession;

import java.lang.reflect.ParameterizedType;
import java.util.HashMap;
import java.util.Map;

public class MapperRegistry {
    private Configuration configuration;
    private Map<Class<?>, MapperProxyFactory<?>> knowMappers = new HashMap<>();

    public MapperRegistry(Configuration configuration) {
        this.configuration = configuration;
    }

    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) this.knowMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new BindingException("没有找到对应的mapper代理, type=" + type.getName());
        }
        return mapperProxyFactory.newInstance(sqlSession);
    }

    public <T> boolean hasMapper(Class<T> type) {
        return this.knowMappers.containsKey(type);
    }

    public void addMapper(Class<?> type) {
        if (type.isInterface()) {
            if (hasMapper(type)) {
                throw new BindingException("类型【" + type + "】已经存在");
            }
            this.knowMappers.put(type, new MapperProxyFactory<>(type));
        }
    }
}
